//
//  NSPointerArray+Additions.swift
//  MGExtensionsKit
//
//  Created by Max on 2020/11/10.
//

import Foundation

extension Extensive where Base == NSPointerArray {
    
    public func add(_ object: AnyObject?) {
        guard let strongObject = object else {
            return
        }
        let pointer = Unmanaged.passUnretained(strongObject).toOpaque()
        base.addPointer(pointer)
    }
    
    public func removeLast() {
        if base.count > 0 {
            base.removePointer(at: base.count - 1)
        }
    }
    
    public func insert(_ object: AnyObject?, at index: Int) {
        guard index < base.count, let strongObject = object else {
            return
        }
        let pointer = Unmanaged.passUnretained(strongObject).toOpaque()
        base.insertPointer(pointer, at: index)
    }
    
    public func replace(at index: Int, withObject object: AnyObject?) {
        guard index < base.count, let strongObject = object else { return }
        
        let pointer = Unmanaged.passUnretained(strongObject).toOpaque()
        base.replacePointer(at: index, withPointer: pointer)
    }
    
    public func object(at index: Int) -> AnyObject? {
        guard index < base.count, let pointer = base.pointer(at: index) else { return nil }
        return Unmanaged<AnyObject>.fromOpaque(pointer).takeUnretainedValue()
    }
    
    public func remove(at index: Int) {
        guard index < base.count else { return }
        base.removePointer(at: index)
    }
}
